package com.atguigu.datastream.test.day06;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * ClassName: Flink06_Flink_Timer_EventTime
 * Package: com.atguigu.test.day06
 * Description:
 *               基于事件时间的定时器
 * @Author ChenJun
 * @Create 2023/4/13 10:15
 * @Version 1.0
 */
public class Flink06_Flink_Timer_EventTime {
    public static void main(String[] args) throws Exception {

        //1. 创建流的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2. 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3. 将数据转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[1], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        })
                //定义watermark
                .assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000;
                    }
                }));

        //4. 将相同的key聚合到一起
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorStream.keyBy("id");

        //TODO 5.使用基于事件时间的定时器
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<Tuple, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                // TODO 定时时间为5s 5s后定时器触发打印一句话
                //获取当前的事件事件
                Long curTime = ctx.timestamp();
                long time = curTime +5000;
                System.out.println("事件事件："+(curTime/1000));
                ctx.timerService().registerEventTimeTimer(time);
            }

            @Override
            public void onTimer(long timestamp, KeyedProcessFunction<Tuple, WaterSensor, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
                out.collect("报警事件："+timestamp / 1000);
            }
        }).print();

        env.execute();
    }
}
